package cn.dapeng.features;

import cn.dapeng.util.SleepingUtil;
import lombok.val;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 共享锁 读
 * 排他锁 写
 */
public class ReadWriteLock_T01 {

    static Lock lock = new ReentrantLock();

    private static int value;

    static Random rand = new Random(100);

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();


    public static void read(Lock lock) {
        try {
            lock.lock();
            SleepingUtil.sleep(1, TimeUnit.SECONDS);
            System.out.println("read over" + value);
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock, int v) {
        try {
            lock.lock();
            SleepingUtil.sleep(1, TimeUnit.SECONDS);
            value = v;
            System.out.println("write over");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        //Runnable readR = () -> read(lock);
        Runnable readR = () -> read(readLock);

        //Runnable writeR = () -> write(lock, rand.nextInt());
        Runnable writeR = () -> write(writeLock, rand.nextInt());

        for (int i = 0; i < 10; i++) {
            new Thread(readR).start();
        }

        for (int i = 0; i < 2; i++) {
            new Thread(writeR).start();
        }


    }
}
